package handlers

import (
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promhttp"
)

var (
	// HTTP metrics
	httpRequestsTotal = prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Name: "devops_smartbot_http_requests_total",
			Help: "Total number of HTTP requests",
		},
		[]string{"method", "endpoint", "status"},
	)

	httpRequestDuration = prometheus.NewHistogramVec(
		prometheus.HistogramOpts{
			Name:    "devops_smartbot_http_request_duration_seconds",
			Help:    "HTTP request duration in seconds",
			Buckets: prometheus.DefBuckets,
		},
		[]string{"method", "endpoint"},
	)

	// Alert metrics
	alertsTotal = prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Name: "devops_smartbot_alerts_total",
			Help: "Total number of alerts",
		},
		[]string{"severity", "status"},
	)

	// Ticket metrics
	ticketsTotal = prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Name: "devops_smartbot_tickets_total",
			Help: "Total number of tickets",
		},
		[]string{"priority", "status"},
	)

	// Notification metrics
	notificationsTotal = prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Name: "devops_smartbot_notifications_total",
			Help: "Total number of notifications sent",
		},
		[]string{"channel", "status"},
	)

	// Active users
	activeUsers = prometheus.NewGauge(
		prometheus.GaugeOpts{
			Name: "devops_smartbot_active_users",
			Help: "Number of active users",
		},
	)
)

func init() {
	// Register metrics
	prometheus.MustRegister(httpRequestsTotal)
	prometheus.MustRegister(httpRequestDuration)
	prometheus.MustRegister(alertsTotal)
	prometheus.MustRegister(ticketsTotal)
	prometheus.MustRegister(notificationsTotal)
	prometheus.MustRegister(activeUsers)
}

// MetricsHandler serves Prometheus metrics
func MetricsHandler() gin.HandlerFunc {
	h := promhttp.Handler()
	return func(c *gin.Context) {
		h.ServeHTTP(c.Writer, c.Request)
	}
}

// MetricsMiddleware records HTTP metrics
func MetricsMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		timer := prometheus.NewTimer(httpRequestDuration.WithLabelValues(c.Request.Method, c.FullPath()))
		defer timer.ObserveDuration()

		c.Next()

		status := c.Writer.Status()
		httpRequestsTotal.WithLabelValues(c.Request.Method, c.FullPath(), http.StatusText(status)).Inc()
	}
}

// RecordAlert records alert metrics
func RecordAlert(severity, status string) {
	alertsTotal.WithLabelValues(severity, status).Inc()
}

// RecordTicket records ticket metrics
func RecordTicket(priority, status string) {
	ticketsTotal.WithLabelValues(priority, status).Inc()
}

// RecordNotification records notification metrics
func RecordNotification(channel, status string) {
	notificationsTotal.WithLabelValues(channel, status).Inc()
}

// UpdateActiveUsers updates active users gauge
func UpdateActiveUsers(count float64) {
	activeUsers.Set(count)
}
